package com.netease.nim.demo.session.viewholder;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.netease.nim.demo.common.adapter.TViewHolder;
import com.netease.nim.demo.common.ui.imageview.HeadImageView;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.cache.TeamMemberInfoCache;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.audio.MessageAudioControl;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nim.demo.util.TimeUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw.activity.ChatPersonalInfoActivity;
import com.shwread.android.qysw10000182.R;
import com.squareup.picasso.Picasso;

import java.io.Serializable;

import logic.bean.GroupBean;
import logic.bean.TeamMemberX;
import logic.constants.Const;
import logic.dao.GroupDao;
import logic.util.ScreenUtil;


public abstract class MsgViewHolder
        extends
        TViewHolder
{
	protected static int	VIEW_HOLDER_LEFT		 = 0;
	protected static int	VIEW_HOLDER_RIGHT		 = 1;
													 
	public static int		MAX_AUDIO_TIME_SECOND	 = 120;
	public static final int	CLICK_TOPLAY_AUDIO_DELAY = 500;
													 
	protected MsgListItem	messageItem;
							
	protected HeadImageView	headImageView;
	protected View			alertButton;
	protected TextView		timeTextView;
	protected View			longClickView;
	protected ProgressBar	progressBar;
	protected View			progressLayout;
	protected TextView		alreadyReadText;
	protected TextView		nameTextView;
							
	protected abstract int getViewHolderDirection();
	
	public interface ViewHolderEventListener
	{
		boolean onViewHolderLongClick(View clickView, View viewHolderView, MsgListItem item);
		
		// resend for viewholderRight
		void onResendButtonPressed(IMMessage resendMessage);
		
		// redownload for viewholderLeft
		void onRedownloadButtonPressed(IMMessage message);
		
		void onAudioStartPlay();
		
		void onAudioEndPlay();
		
		void onAtlasPressed(String imagelist);
		
		void onHeadImagePressed(Object item);
		
		void onHeadImageLongPressed(Object item);
	}
	
	protected ViewHolderEventListener eventListener;
	
	public void setEventListener(ViewHolderEventListener eventListener) {
		this.eventListener = eventListener;
		if (messageItem != null && messageItem.getMessage() != null)
		{
			setEvent(messageItem.getMessage());
		}
	}
	
	@Override
	protected void inflate() {
		timeTextView = (TextView) view.findViewById(R.id.textViewTime);
		headImageView = (HeadImageView) view.findViewById(R.id.imageViewHead);
		alertButton = view.findViewById(R.id.buttonMessageAlert);
		if (getViewHolderDirection() == VIEW_HOLDER_RIGHT)
		{
			progressBar = (ProgressBar) view.findViewById(R.id.msg_progressBar);
			alreadyReadText = (TextView) view.findViewById(R.id.textViewAlreadyRead);
		}
		nameTextView = (TextView) view.findViewById(R.id.textViewName);
		
	}
	
	@Override
	protected void refresh(Object item) {
		messageItem = (MsgListItem) item;
		setHeadImageView(messageItem);
		setNameTextView(messageItem.getMessage());
		setTimeTextView(messageItem);
		setStatus(messageItem);
		setEvent(messageItem.getMessage());
		setLongClickListener(messageItem);
		showReadReceipt(messageItem.getMessage());
	}
	
	public void refreshCurrentItem() {
		if (messageItem != null)
		{
			refresh(messageItem);
		}
	}
	
	protected void setTimeTextView(final MsgListItem messageItem) {
		if (messageItem.needShowTime)
		{
			timeTextView.setVisibility(View.VISIBLE);
		}
		else
		{
			timeTextView.setVisibility(View.GONE);
			return;
		}
		
		String text = TimeUtil.getTimeShowString(messageItem.getMessage().getTime(), false);
		timeTextView.setText(text);
	}
	
	protected void setStatus(final MsgListItem messageItem) {
		MsgStatusEnum status = messageItem.getMessage().getStatus();
		switch (status) {
			case fail:
				if (progressBar != null)
				{
					progressBar.setVisibility(View.GONE);
				}
				if (progressLayout != null)
				{
					progressLayout.setVisibility(View.GONE);
				}
				alertButton.setVisibility(View.VISIBLE);
				break;
			case sending:
				if (progressBar != null)
				{
					progressBar.setVisibility(View.VISIBLE);
				}
				if (progressLayout != null)
				{
					progressLayout.setVisibility(View.VISIBLE);
				}
				alertButton.setVisibility(View.GONE);
				break;
			default:
				if (progressBar != null)
				{
					progressBar.setVisibility(View.GONE);
				}
				if (progressLayout != null)
				{
					progressLayout.setVisibility(View.GONE);
				}
				alertButton.setVisibility(View.GONE);
				break;
		}
	}
	
	protected void setHeadImageView(final MsgListItem messageItem) {
		TeamMemberX bean = TeamMemberInfoCache.getInstance().getTeammMemberInfo(messageItem.getMessage().getFromAccount());
		headImageView.loadBuddyHeadImage(messageItem.getMessage().getFromAccount());
		if (null != bean && !TextUtils.isEmpty(bean.getHeadImage()))
		{
			//    		ImageLoaderUtil.loadWebUrl(bean.getHeadImage(), headImageView);
			Picasso.with(context).load(bean.getHeadImage()).into(headImageView);
		}
	}
	
	protected void setEvent(final IMMessage message) {
		if (eventListener == null) { return; }
		
		if (getViewHolderDirection() == VIEW_HOLDER_LEFT)
		{
			// 重新下载
			alertButton.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					if (null != eventListener)
			                                   eventListener.onRedownloadButtonPressed(message);
				}
			});
			
		}
		else
		{
			// 重新发送
			alertButton.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					if (null != eventListener)
			                                   eventListener.onResendButtonPressed(message);
				}
			});
		}
		
		headImageView.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				AddressBookInfoDao addressBookInfoDao = AddressBookInfoDao.getInstance(context);
				if (messageItem.getMessage().getSessionType().equals(SessionTypeEnum.Team))
				{
					if (getViewHolderDirection() == VIEW_HOLDER_LEFT)
					{
						P2PMessageActivity.start(context, messageItem.getMessage().getFromAccount());
					}
					return;
				}
				
				if (addressBookInfoDao.getById(getViewHolderDirection() == VIEW_HOLDER_LEFT ? messageItem.getMessage().getSessionId() : Const.UserAccId) == null)
		                                                                                                                                                          return;
				AddressBookInfo addressBookInfo = addressBookInfoDao.getById(getViewHolderDirection() == VIEW_HOLDER_LEFT ? messageItem.getMessage().getSessionId() : Const.UserAccId);
				GroupDao groupDao = GroupDao.getInstance(context);
				if (groupDao.getById(addressBookInfo.getGroupId()) == null)
		                                                                    return;
				GroupBean groupBean = groupDao.getById(addressBookInfo.getGroupId());
				Intent intent = new Intent(context, ChatPersonalInfoActivity.class);
				intent.putExtra("contactInfo", (Serializable) addressBookInfo);
				intent.putExtra("groupName", groupBean.getName());//mGroupData.get(groupPosition).getName()
				context.startActivity(intent);
				
			}
			
		});
		
	}
	
	protected void redownload() {
		downloadMessage(messageItem.getMessage());
	}
	
	protected void downloadMessage(IMMessage message) {
		NIMClient.getService(MsgService.class).downloadAttachment(message, true);
	}
	
	public static int getImageDefWidth() {
		return getImageMaxEdge();
	}
	
	public static int getImageMaxEdge() {
		return (int) (165.0 / 320.0 * ScreenUtil.screenWidth);
	}
	
	public static int getImageMinEdge() {
		return (int) (76.0 / 320.0 * ScreenUtil.screenWidth);
	}
	
	public static int getAudioMaxEdge() {
		return (int) (0.6 * ScreenUtil.screenMin);
	}
	
	public static int getAudioMinEdge() {
		return (int) (0.1875 * ScreenUtil.screenMin);
	}
	
	public static int getImageDefHeight() {
		return getImageMaxEdge();
	}
	
	public static int getLocationDefEdge() {
		return (int) (0.5 * ScreenUtil.screenWidth);
	}
	
	public static int calculateBubbleWidth(long seconds, int MAX_TIME) {
		int maxAudioBubbleWidth = getAudioMaxEdge();
		int minAudioBubbleWidth = getAudioMinEdge();
		
		int currentBubbleWidth;
		if (seconds <= 0)
		{
			currentBubbleWidth = minAudioBubbleWidth;
		}
		else if (seconds > 0 && seconds <= MAX_TIME)
		{
			currentBubbleWidth = (int) ((maxAudioBubbleWidth - minAudioBubbleWidth) * (2.0 / Math.PI) * Math.atan(seconds / 10.0) + minAudioBubbleWidth);
		}
		else
		{
			currentBubbleWidth = maxAudioBubbleWidth;
		}
		
		if (currentBubbleWidth < minAudioBubbleWidth)
		{
			currentBubbleWidth = minAudioBubbleWidth;
		}
		else if (currentBubbleWidth > maxAudioBubbleWidth)
		{
			currentBubbleWidth = maxAudioBubbleWidth;
		}
		
		return currentBubbleWidth;
	}
	
	protected void setLayoutParams(int width, int height, View... views) {
		for (View view : views)
		{
			LayoutParams maskParams = view.getLayoutParams();
			maskParams.width = width;
			maskParams.height = height;
			view.setLayoutParams(maskParams);
		}
	}
	
	protected void startAnimation(AnimationDrawable animationDrawable, View playAudioButton, boolean left) {
		if (animationDrawable != null)
		{
			animationDrawable.start();
			playAudioButton.setBackgroundResource(left ? R.drawable.message_audio_playing_left_blue_bg : R.drawable.message_audio_playing_right_blue_bg);
		}
	}
	
	protected void stopAnimation(AnimationDrawable animationDrawable, View playAudioButton, boolean left) {
		if (animationDrawable != null && animationDrawable.isRunning())
		{
			animationDrawable.stop();
			playAudioButton.setBackgroundResource(left ? R.drawable.bg_message_left_selector : R.drawable.bg_message_right_selector);
		}
	}
	
	protected boolean isMessagePlaying(MessageAudioControl audioControl, IMMessage message) {
		if (audioControl.getPlayingAudio() != null && audioControl.getPlayingAudio().isTheSame(message))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * item长按事件监听
	 *
	 * @param item
	 */
	protected void setLongClickListener(final MsgListItem item) {
		if (longClickView != null)
		{
			longClickView.setOnLongClickListener(new View.OnLongClickListener()
			{
				@Override
				public boolean onLongClick(View v) {
					if (eventListener != null)
					{
						eventListener.onViewHolderLongClick(longClickView, view, item);
						return true;
					}
					else
					{
						return false;
					}
				}
			});
		}
	}
	
	// 已读
	protected void showReadReceipt(IMMessage message) {
		if (alreadyReadText == null)
		                             return;
		if (message.getStatus() == MsgStatusEnum.read)
		{
			alreadyReadText.setVisibility(View.VISIBLE);
		}
		else
		{
			alreadyReadText.setVisibility(View.GONE);
		}
	}
	
	protected void setNameTextView(final IMMessage message) {
		if (getViewHolderDirection() == VIEW_HOLDER_RIGHT) { return; }
		
		if (message.getSessionType() == SessionTypeEnum.Team)
		{
			nameTextView.setVisibility(View.VISIBLE);
			final String name = TeamDataCache.getInstance().getDisplayNameWithoutMe(message.getSessionId(), message.getFromAccount());
			nameTextView.setText(name);
			//            nameTextView.setText(TeamDataCache.getInstance().getTeamMemberDisplayName(message.getSessionId(), message.getFromAccount()));
		}
		else
		{
			nameTextView.setVisibility(View.GONE);
		}
	}
}
